package org.example.servlet;

import org.example.WebMvcContext;
import org.example.handler.MethodHandler;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 写点什么？
 *
 * @author hrz
 * @since 2021/3/2 0002
 */
public class DispatcherServlet extends HttpServlet {

    private WebMvcContext webMvcContext;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        webMvcContext = (WebMvcContext) config.getServletContext().getAttribute(WebMvcContext.CONTEXT_NAME);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String requestUri = req.getRequestURI();
        System.out.println(DispatcherServlet.class.getName()+" 处理请求："+requestUri);
        MethodHandler requestMethod = webMvcContext.match(requestUri);
        try {
            if (requestMethod == null) {
                resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            requestMethod.handle(req, resp);
        } catch (Throwable e) {
            e.printStackTrace();
            throw new ServletException("当前请求方法【"+requestMethod.name()+"】处理异常！",e);
        }
    }

}
